#include "musicplayer.h"
#include "ui_musicplayer.h"
#include "songmanager.h"
#include <QMouseEvent>
#include <QDebug>
#include <QGroupBox>
#include <QLabel>
#include <QScrollArea>
#include <QTimer>
#include <QShortcut>
#include <QPainter>
#include <QMenu>

MusicPlayer::MusicPlayer(QWidget *parent)
    : QWidget(parent)
    , dx(0), dy(0)
    , _viewSwitchButtons(9, nullptr)
    , _searchList(new SearchListWidget(this))
    , _playPage(new PlayPageWidget(this))
    , _player(new QMediaPlayer(this))
    , _playlist(new QMediaPlaylist(this))
    , _volumeTool(new VolumeToolWidget(this))
    , ui(new Ui::MusicPlayer)
{
    ui->setupUi(this);
    initUI();
    ui->page_liked_music->setListId(0);
    connect(_searchList, &SearchListWidget::played, this, &MusicPlayer::on_songItem_played);
    connect(_searchList, &SearchListWidget::playAll, this, &MusicPlayer::on_songItem_playAll);
    connect(ui->page_local, &LocalListWidget::played, this, &MusicPlayer::on_songItem_played);
    connect(ui->page_local, &LocalListWidget::playAll, this, &MusicPlayer::on_songItem_playAll);
    connect(ui->page_liked_music, &PlaylistWidget::played, this, &MusicPlayer::on_songItem_played);
    connect(ui->page_liked_music, &PlaylistWidget::playAll, this, &MusicPlayer::on_songItem_playAll);

    QShortcut *spaceShortcut = new QShortcut(QKeySequence(Qt::Key_Space), this);
    connect(spaceShortcut, &QShortcut::activated, ui->pushButton_playPause, &QPushButton::click);
    connect(_player, &QMediaPlayer::stateChanged, this, &MusicPlayer::on_player_stateChanged);
//    connect(_playlist, &QMediaPlaylist::mediaChanged, this, &MusicPlayer::on_playlist_mediaFirstChanged);
    connect(_playlist, &QMediaPlaylist::playbackModeChanged, this, &MusicPlayer::on_playlist_playbackModeChanged);
    connect(_playlist, &QMediaPlaylist::currentIndexChanged, this, &MusicPlayer::on_playlist_currentIndexFChanged);
    _playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);

    _player->setVolume(30);
    _player->setPlaylist(_playlist);
    connect(SongManager::instance(), &SongManager::liked, ui->page_liked_music, &PlaylistWidget::on_SongManager_liked);
//    QTimer::singleShot(1000, this, [this](){this->ui->page_local->flush();});


    _viewSwitchButtons[5]->selected(true);



    // 音量按钮弹窗的处理
    ui->pushButton_volume->installEventFilter(this);
    _volumeTool->installEventFilter(this);
    connect(_volumeTool, &VolumeToolWidget::volumeChanged, this, [=](int volume){
        _player->setVolume(volume);
        QString image;
        if(volume == 0){
            image = "noVolume"; // 静音图片
        } else {
            image = "Volume";// 不是静音的图片
        }
        QString style = "QPushButton {"
                            "background-repeat: no-repeat;"
                            "background-position: center;"
                            "background-image: url(:/image/ui/btn_" + image + ".png);"
                            "border: none;"
                            "background-color: transparent;"
                        "}";
        ui->pushButton_volume->setStyleSheet(style);
    });
}

MusicPlayer::~MusicPlayer()
{
    delete ui;
}

void MusicPlayer::initUI()
{
    initMainWindow(); // 初始化大窗口

    allowWindowChangeSize(true); // 若允许, 可点击左上角指定区域(黄色), 缩放窗口

    initBodyLeft();

    initPlaybackControlPanel();

    initSearch();

    initPlayPage();

    initTray(); // 托盘
}

#include <QGraphicsDropShadowEffect>
void MusicPlayer::initMainWindow()
{
    setWindowFlag(Qt::FramelessWindowHint); // 无标题栏, 拖动功能会被ban掉, 需手写mouseXXXEvent

    // 设置阴影:
    setAttribute(Qt::WA_TranslucentBackground); // 窗口背景透明。这个不添加会很黑
    QGraphicsDropShadowEffect* effect = new QGraphicsDropShadowEffect(this);
    effect->setColor(Qt::black);
    effect->setOffset(0, 0); // 0偏移。这个不设置会有点偏, 立体感?
    effect->setBlurRadius(6);
    setGraphicsEffect(effect);
}

void MusicPlayer::mousePressEvent(QMouseEvent *event)
{
//    下面这种写法，在鼠标按下按钮，然后滑动到界面中时会出bug
//    按下的是按钮，dx、dy不更新，滑动到界面，MoveEvent会触发
//    dx = event->x();
//    dy = event->y();
//    qDebug() << dx << ' ' << dy;

    QRect geometry = ui->playbackControlPanel->geometry();
    QPoint globalP = ui->playbackControlPanel->mapToGlobal({0, 0});
    if(QRect(globalP.x(), globalP.y(), geometry.width(), geometry.height()).contains(event->globalPos())){
        qDebug() << "控制板被点击";
        _playPage->movePage();
    }
    QWidget::mousePressEvent(event);
}

void MusicPlayer::mouseMoveEvent(QMouseEvent *event)
{
//    qDebug() << event->buttons();
    if(event->buttons() == Qt::LeftButton){
        if(!dx && !dy){
            dx = event->x();
            dy = event->y();
        }
        if(dy > ui->head->height() || dx > ui->head->width());
        else // 只能通过头部区域拖动窗口
        {
            int x = event->globalX() - dx;
            int y = event->globalY() - dy;
            move(x, y);
//            qDebug() << "move to : " << x << ' ' << y;
            return;
        }
    }

    QWidget::mouseMoveEvent(event);
}

void MusicPlayer::mouseReleaseEvent(QMouseEvent *event)
{
//    qDebug() << event->buttons(); // 始终是: QFlags<Qt::MouseButton>(NoButton)
    if(dx || dy) {
        dx = dy = 0;
        return;
    }
    QWidget::mouseReleaseEvent(event);
}

#include <QSizeGrip>
void MusicPlayer::allowWindowChangeSize(bool jug)
{
    if(jug){
        // 允许窗口调整大小
        setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

        // 创建大小调整手柄并添加到右下角
        QSizeGrip *sizeGrip = new QSizeGrip(this);
        // 设置大小调整手柄的样式和位置
        sizeGrip->setStyleSheet("background-color: transparent;");
        // 添加布局来定位大小调整手柄
        QGridLayout *layout = new QGridLayout(this);
        layout->addWidget(sizeGrip, 1, 1, 1, 1, Qt::AlignBottom | Qt::AlignRight);
        layout->setContentsMargins(0, 0, 0, 0);
        sizeGrip->raise();
        sizeGrip->show();
    }
}

void MusicPlayer::initPlaybackControlPanel()
{
    QString name = "暂未播放";
    QString artist = "暂无";
    QString htmlText = "<span style='font-family:Microsoft YaHei; font-size:23px; color:#283248;'>" + name + "</span>"
                       "<span style='font-family:Microsoft YaHei; font-size:21px; color:#9ca3af;'> - " + artist +"</span>";
    ui->label_songNameAndArtist->setText(htmlText);
    ui->label_songNameAndArtist->setTextFormat(Qt::RichText);  // 确保是富文本模式
    ui->label_songImage->setAlignment(Qt::AlignCenter);

    connect(_player, &QMediaPlayer::positionChanged, ui->slider, &MusicSliderWidget::setCurTime);
    connect(_player, &QMediaPlayer::positionChanged, _playPage, &PlayPageWidget::setCurTime);
    connect(ui->slider, &MusicSliderWidget::changeTime, this, [=](qint64 value){
        _player->setPosition(value);
    });
    connect(SongManager::instance(), &SongManager::liked, this, [=](QUrl url, bool isLike){
        if (url == _currentUrl){
            updateLikeButton(isLike);
        }
    });
}

void MusicPlayer::initSearch()
{
    ui->pages->addWidget(_searchList);
    ui->pages->removeWidget(_searchList); // 初始化位置
    QStringList* recomment = new QStringList{QString("kyiku"), QString("rinri"), QString("Orangestar"), QString("n-buna"),
    QString("ピノキオピー"), QString("DECO*27"), QString("内緒のピアス"), QString("香椎モイミ"), QString("イマニシ"), QString("ララコン カワニ")};
    ui->lineEdit_search->setPlaceholderText((*recomment)[0]);
    static int curIndex = 1;
    QTimer* controlSearchRecomment = new QTimer(this);
    connect(controlSearchRecomment, &QTimer::timeout, this, [=](){
        if(curIndex >= recomment->size()) curIndex = 0;
        ui->lineEdit_search->setPlaceholderText((*recomment)[curIndex]);
        curIndex++;
    });
    controlSearchRecomment->start(5000);
}

void MusicPlayer::initPlayPage()
{
    _playPage->hide();
//    connect(_playPage, &PlayPageWidget::changeColor, this, &MusicPlayer::changePlayBackColor);
    //    _playPage->movePage();
}

void MusicPlayer::initTray()
{
    _tray = new QSystemTrayIcon(this);
    _tray->setIcon(QIcon(":/image/ui/windowIcon.png"));
    _tray->show();

    QMenu* menu = new QMenu(this);
    menu->addAction("退出", this, &MusicPlayer::exit);
    _tray->setContextMenu(menu); // 设置了菜单, 点击右键自动弹出
    // TODO: 菜单改成自定义弹窗

    // 捕获托盘图标的点击事件
    connect(_tray, &QSystemTrayIcon::activated, this, [=](QSystemTrayIcon::ActivationReason reason) {
        if (reason == QSystemTrayIcon::Trigger) {
            this->showNormal();
            raise(), activateWindow(); // 放到最上面+变成活动窗口
        }
    });

    _tray->show(); // 显示,这句必须加
}

void MusicPlayer::exit()
{
    // 这里保存速度有点慢，所以先隐藏一下窗口，这样保存再慢也不影响观感
    on_pushButton_closeWindow_clicked(); // 欸嘿
    _tray->hide(); // 欸嘿嘿
    SongManager::instance()->storage();
    close();
}

void MusicPlayer::beginPlay(QUrl url)
{
    if (_currentUrl != url) {
//        disconnect(_player, &QMediaPlayer::stateChanged, this, &MusicPlayer::on_player_stateChanged);
//        qDebug() << "url不同, 此时player的状态：" <<_player->state() << ",下面准备递归调用更新时间";
//        beginPlay(_currentUrl); // setMedia会触发_player的stateChanged信号,所以这里先更新一下图片暂停旋转的总时间
//        qDebug() << "递归调用结束";
//        _songImageSumPausedTime += _songImageElapsedTimer.elapsed() - _songImageLastPausedTime;
        // 总结了一下,这里只会出现PlayingState和PausedState
        // 那直接条件判断更新暂停总时间即可:
//        if (_player->state() == QMediaPlayer::PausedState){
//            _songImageSumPausedTime += _songImageElapsedTimer.elapsed() - _songImageLastPausedTime;
//        }
        // 发现问题没解决,问题：歌曲终止播放后,无法切换媒体到下一首歌曲
//        _player->stop();

//        _playlist->clear();
//        _currentSongs.clear();
        int index = _currentSongs.indexOf(url);
        if (index == -1) {
            _currentSongs.push_back(url);
            _playlist->addMedia(url);
            index = _currentSongs.size() - 1;
        }

//        while(_playlist->) QCoreApplication::processEvents();
        qDebug() << "cur _playlist medias : " << _playlist->mediaCount();

//        _playlist->next();
        _playlist->setCurrentIndex(index);
//        _player->setMedia(url);
        _currentUrl = url;
//        connect(_player, &QMediaPlayer::stateChanged, this, &MusicPlayer::on_player_stateChanged);
    }
    if (_currentUrl.isEmpty()) { // 程序启动就按按钮的情况
        ui->pushButton_playPause->setChecked(false);
        return;
    }
    ui->pushButton_playPause->setChecked(true); // 设置大按钮的状态

    // 恢复旋转:
    if(!_songImageTimer->isActive()){
        qDebug() << "------------------------" << url << "------------------------";
        qDebug() << QString::asprintf("在%lld时,更新了总暂停时间,更新前为%lld", _songImageElapsedTimer.elapsed(), _songImageSumPausedTime);
        _songImageSumPausedTime += _songImageElapsedTimer.elapsed() - _songImageLastPausedTime;
        _songImageLastPausedTime = _songImageElapsedTimer.elapsed();
        qDebug() << QString::asprintf("在%lld时,更新了总暂停时间,更新后为%lld", _songImageElapsedTimer.elapsed(), _songImageSumPausedTime);
        qDebug() << "------------------------" << url << "------------------------";
        _songImageTimer->start();
    }

    // 然后开始播放:
    _player->play();

//    emit SongManager::instance()->played(_currentUrl, true);
    SongManager::instance()->play(_currentUrl, true);
}

void MusicPlayer::stopPlay()
{
    _player->pause(); // 暂停播放
    ui->pushButton_playPause->setChecked(false); // 设置大按钮的状态

    _songImageTimer->stop(); // 暂停旋转
//    emit SongManager::instance()->played(_currentUrl, false);
    SongManager::instance()->play(_currentUrl, false);
}

void MusicPlayer::updateSongMessage(const SongItem& songItem)
{
    QString name = songItem.name;
    QString artist = songItem.artist;
    QString htmlText = "<span style='font-family:Microsoft YaHei; font-size:23px; color:#283248;'>" + name + "</span>"
                       "<span style='font-family:Microsoft YaHei; font-size:21px; color:#9ca3af;'> - " + artist +"</span>";
    ui->label_songNameAndArtist->setText(htmlText);
    updateCurrentSongImage(songItem.image);
    ui->slider->setSumTime(songItem.duration);
    updateLikeButton(songItem.isLike);
    _playPage->updateCurUrl(songItem.url());
}

void MusicPlayer::updateCurrentSongImage(const QPixmap& image)
{
    QSize size = ui->label_songImage->size();
    QPixmap scaledSongImage = image.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    _currentSongImage = QPixmap(size);
    _currentSongImage.fill(Qt::transparent);

    QPainter painter(&_currentSongImage);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QBrush(scaledSongImage));
    painter.drawRoundedRect(scaledSongImage.rect(), 30, 30);
    _playPage->updateCurrentSongImage(image);
}

void MusicPlayer::updateLikeButton(bool isLike)
{
    QString image;
    if (isLike){
        image = "like_r";
    } else {
        image = "like_w";
    }
    QString style = "QPushButton {"
                        "background-repeat: no-repeat;"
                        "background-position: center;"
                        "background-image: url(:/image/ui/songitem/" + image + "_50.png);"
                        "border: none;"
                        "background-color: transparent;"
                    "}"
                    "QPushButton:hover"
                    "{ background-image: url(:/image/ui/songitem/" + image + "_100.png); }";
    ui->pushButton_like->setStyleSheet(style);
}

void MusicPlayer::initSongImageTimer()
{
    _songImageTimer = new QTimer(this);
    _songImageElapsedTimer.restart();
    _songImageSumPausedTime = 0;
    _songImageLastPausedTime = 0;
    qDebug() << "_songImageElapsedTimer restart:" << _songImageElapsedTimer.elapsed();
    // 设置定时器
    connect(_songImageTimer, &QTimer::timeout, this, [=](){
//        qDebug() << "-----------";
//        qDebug() << QString::asprintf("当前时间:%lld, 最后暂停:%lld, 总共暂停:%lld", _songImageElapsedTimer.elapsed(), _songImageLastPausedTime, _songImageSumPausedTime);
//        qDebug() << "-----------";

        // 用实际经过的时间计算角度,且保证精确(终于不会一会儿快一会儿慢了!!)
        _songImageLastPausedTime = _songImageElapsedTimer.elapsed();   // 记录最后更新时间,等计时器停了,这就是最新的暂停时间
        qint64 elapsed = _songImageLastPausedTime - _songImageSumPausedTime;
        _songImageRotationAngle = (elapsed % 40000) * 360.0 / 40000.0; // 40000ms ~ 360

        // 创建变换矩阵,注:记得每次重新创建,不然会有状态叠加等奇奇怪怪的问题
        QTransform transform;
        QPointF center(_currentSongImage.width()/2.0, _currentSongImage.height()/2.0);
        // 默认绕着(0,0)即父控件左上角转
        // 由于Qt::AlignCenter的作用,
        // 图像虽然呈现在了中心,但是会一直抖动.
        // 所以旋转前后得设置旋转中心
        transform.translate(center.x(), center.y());
        transform.rotate(_songImageRotationAngle);
        transform.translate(-center.x(), -center.y());

        QPixmap rotatedPixmap = _currentSongImage.transformed(transform, Qt::SmoothTransformation);
        ui->label_songImage->setPixmap(rotatedPixmap);
        _playPage->setAngleOfImage(_songImageRotationAngle);
    });
    _songImageTimer->start(16); // 1000/33 ~ 30帧一秒, 这个和实际旋转角度无关, 这是刷新ui的频率
    ui->widget_songImage->setStyleSheet(""); // 清除白色背景,不然会有毛毛边
}

void MusicPlayer::changePlayBackColor(const QString &color)
{
    qDebug() << "changePlayBackColor to : " << color;
    QString style = "#playbackControlPanel {background-color:" + color + "; border-bottom-left-radius: 12px; border-bottom-right-radius: 12px;}";
    ui->playbackControlPanel->setStyleSheet(style);
}

// 这部分拖着太麻烦, 搞了很久没搞出来, 最后选择用代码写
void MusicPlayer::initBodyLeft()
{
    // 主布局
    QLayout *mainLayout = ui->bodyLeft->layout();
    mainLayout->setContentsMargins(0, 0, 9, 0); // 这里一定记得设, 不然后面会有几个像素的差距

    // QScrollArea 及其内部容器
    QScrollArea *scrollArea = ui->scrollArea;
    QLayout *containerLayout = ui->container->layout();
    containerLayout->setSpacing(6);                   // 控件间固定 6px 间距
    containerLayout->setContentsMargins(35, 0, 0, 0);    // 左边距 35
    containerLayout->setAlignment(Qt::AlignTop);       // 布局内所有子控件顶对齐

    // scrollArea
    scrollArea->setWidgetResizable(true);

    //上半部分的纯代码版, 已舍去:
    //void MusicPlayer::initBodyLeft()
    //{
    //    // 1) 新建一个主布局，设置给 ui->bodyLeft
    //    QVBoxLayout *mainLayout = new QVBoxLayout(ui->bodyLeft);
    //    mainLayout->setContentsMargins(0, 0, 9, 0); // 这里一定记得设, 不然后面会有几个像素的差距

    //    // 2) 新建 QScrollArea 及其内部容器
    //    QScrollArea *scrollArea = new QScrollArea(ui->bodyLeft);

    //    QWidget *container = new QWidget;
    //    QVBoxLayout *containerLayout = new QVBoxLayout(container);
    //    containerLayout->setSpacing(6);                   // 控件间固定 6px 间距
    //    containerLayout->setContentsMargins(35, 0, 0, 0);    // 左边距 35
    //    containerLayout->setAlignment(Qt::AlignTop);       // 布局内所有子控件顶对齐

    //    container->setLayout(containerLayout);

    //    // 3) 设置 scrollArea
    //    scrollArea->setWidget(container);
    //    scrollArea->setWidgetResizable(true);

    //    // 4) 最关键：将 scrollArea 加到主布局里
    //    mainLayout->addWidget(scrollArea);
    //    下同
    {
        // 占位用的控件
        auto n = new QWidget(ui->bodyLeft);
        n->setMinimumSize(QSize(245, 19)); // 25 - 6 = 19
        n->setMaximumSize(QSize(245, 19));
//        n->setStyleSheet("background-color:red;");
        containerLayout->addWidget(n);
    }

    // 手动添加自定义按钮, 对应推荐、精选、播客、漫游、关注
    for(int i = 0; i < 5; i++) {
        _viewSwitchButtons[i] = new ViewSwitchButton(ui->bodyLeft, i);
        containerLayout->addWidget(_viewSwitchButtons[i]);
        connect(_viewSwitchButtons[i], &ViewSwitchButton::viewSwitchButton_clicked, this, &MusicPlayer::on_viewSwitchButton_clicked);
    }

    {
        QLabel* label = new QLabel(ui->bodyLeft);
        label->setMinimumSize(QSize(245, 26)); // 高 = 40 - 6*2 = 28
        label->setMaximumSize(QSize(245, 26));
//        label->setStyleSheet("background-color:red;");
        containerLayout->addWidget(label);
    }

    for(int i = 5; i < _viewSwitchButtons.size(); i++){
        qDebug() << "index i = " << i;
        _viewSwitchButtons[i] = new ViewSwitchButton(ui->bodyLeft, i);
        containerLayout->addWidget(_viewSwitchButtons[i]);
        connect(_viewSwitchButtons[i], &ViewSwitchButton::viewSwitchButton_clicked, this, &MusicPlayer::on_viewSwitchButton_clicked);
    }

    {
        QLabel* label = new QLabel(ui->bodyLeft);
        label->setMinimumSize(QSize(245, 30)); // 高 = 42 - 6*2 = 30
        label->setMaximumSize(QSize(245, 30));
//        label->setStyleSheet("background-color:red;");
        containerLayout->addWidget(label);
    }

    auto btn = new QPushButton("动态按钮", ui->bodyLeft);
    btn->setMinimumSize(QSize(245, 55));
    btn->setMaximumSize(QSize(245, 55));
    btn->setStyleSheet("QPushButton { background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1,stop:0 #f8f1f8, stop:1 #fbe6ee);border: none;border-radius: 12px;padding: 12px;}QPushButton:hover {background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1,stop:0 #fcdfea, stop:1 #f8c7e1);}");
    containerLayout->addWidget(btn);
    bool* jug = new bool(false);
    connect(btn, &QPushButton::clicked, this, [=](){
        if((*jug = !*jug)){
            for(int i = 0; i < 100; i++){
                auto n = new QPushButton("动态按钮", ui->bodyLeft);
                n->setMinimumSize(QSize(245, 55));
                n->setMaximumSize(QSize(245, 55));
                n->setStyleSheet("QPushButton { background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1,stop:0 #f8f1f8, stop:1 #fbe6ee);border: none;border-radius: 12px;padding: 12px;}QPushButton:hover {background-color: qlineargradient(x1:0, y1:0, x2:1, y2:1,stop:0 #fcdfea, stop:1 #f8c7e1);}");
                QTimer::singleShot(0, this, [=]() {
                    containerLayout->addWidget(n);
                });
            }
        } else {
            QList<QPushButton*> btnList = ui->bodyLeft->findChildren<QPushButton*>();
            int i = 0;
            for(auto btn : btnList){
                i++;
                if(i >= _viewSwitchButtons.size() + 2){
                    delete btn;
                }
            }
        }
    });
//    qDebug() << "Children in container:" << ui->container->children();
}

void MusicPlayer::on_pushButton_closeWindow_clicked()
{
    hide(); // 隐藏就行,close丢给托盘
}

void MusicPlayer::on_viewSwitchButton_clicked(int index)
{
    int old_index = ui->pages->currentIndex();
    qDebug() << "old_index = " << old_index << ", index = " << index;
    if (ui->pages->currentWidget() == _searchList) ui->pages->removeWidget(_searchList);
    if (old_index < _viewSwitchButtons.size()) _viewSwitchButtons[old_index]->selected(false);
    ui->pages->setCurrentIndex(index);
//    if (ui->pages->currentWidget() == ui->page_local) ui->page_local->flush();
    _viewSwitchButtons[index]->selected(true);
}

#include <QGuiApplication>
#include <QScreen>
void MusicPlayer::on_pushButton_fullscreen_clicked()
{
    static bool isFullscreen = false;
    static QRect oldGeometry;
    if (isFullscreen){
        setGeometry(oldGeometry);
    } else {
        oldGeometry = geometry();
        QRect newGeometry = QGuiApplication::primaryScreen()->geometry();
        newGeometry.setX(newGeometry.x() - 10);
        newGeometry.setY(newGeometry.y() - 10);
        newGeometry.setWidth(newGeometry.width() + 10);
        newGeometry.setHeight(newGeometry.height() + 10);
        setGeometry(newGeometry);
//        setGeometry(QGuiApplication::primaryScreen()->geometry());
    }
    isFullscreen = !isFullscreen;
    // TODO:填加图标, 以及全屏后拖拽的处理逻辑
}
#include <QRegularExpression>
void MusicPlayer::on_pushButton_miniMode_clicked()
{

}

void MusicPlayer::on_lineEdit_search_returnPressed()
{
    QString searchText = ui->lineEdit_search->placeholderText();
    if (ui->lineEdit_search->text().size() != 0)
        searchText = ui->lineEdit_search->text();
    if (_searchList) ui->pages->removeWidget(_searchList);
    int old_index = ui->pages->currentIndex();
    if (old_index < _viewSwitchButtons.size()) _viewSwitchButtons[old_index]->selected(false);
//    QTimer::singleShot(0, this, [=]() { // 这里就别用singleShot了,如果一直按照Enter,这里会排队,等会儿搜索界面的ui就会被卡一下
        qDebug() << "搜索 : " << searchText;
        _searchList->search(searchText);
        ui->pages->addWidget(_searchList);
        ui->pages->setCurrentWidget(_searchList);
//    });
}

void MusicPlayer::on_pushButton_search_clicked()
{
    ui->lineEdit_search->returnPressed();
}

void MusicPlayer::on_songItem_played(const SongItem& songItem, bool play)
{
    QUrl url = songItem.url();
    if(url.isEmpty()){ // 先判断,不能让没用的url干扰正常的播放逻辑
        qDebug() << "没用的url";
        return;
    }

    if(play == false){
        stopPlay();
        return;
    }

    qDebug() << "开始播放 : " << url;
    if(_currentUrl != url){
        // 更新底部的歌曲信息
        updateSongMessage(songItem);
    }

//    if(_songImageTimer == nullptr){
//        initSongImageTimer();
//    }

    beginPlay(url);
}

void MusicPlayer::on_songItem_playAll(const QVector<QUrl> &songs)
{
    qDebug() << "播放的歌单有" << songs.size() << "首歌曲";
    if(songs.size() == 0) return;
    _player->pause();
    _playlist->clear();
    _currentSongs.clear();
    _currentSongs = songs;

    for(const auto& url : songs){
        _playlist->addMedia(url);
    }
    _playlist->setCurrentIndex(0);
    qDebug() << "播放一个歌单的" << _playlist->mediaCount() << "首歌曲";
    _currentUrl = _currentSongs[0];
    beginPlay(_currentUrl);
}

void MusicPlayer::on_player_stateChanged(QMediaPlayer::State state)
{
    if (state == QMediaPlayer::StoppedState){
        qDebug() << "state == QMediaPlayer::StoppedState";
//        stopPlay();
//        ui->pushButton_playPause->setChecked(false); // 设置大按钮的状态
//        _songImageLastPausedTime = _songImageElapsedTimer.elapsed(); // 设置最近暂停时间
//        emit SongManager::instance()->played(_currentUrl, false);
        // 5.17 此时进入这个状态,说明手动更新了playlist,无论是单切多,多切单,多切多还是单切单
        if(_songImageTimer->isActive()) _songImageTimer->stop(); // 暂停旋转
    } else if (state == QMediaPlayer::PausedState){
        qDebug() << "state == QMediaPlayer::PausedState";
//        stopPlay();
        if(_songImageTimer->isActive()) _songImageTimer->stop(); // 暂停旋转
    } else {
        qDebug() << "state == " << state;
//        if(!_songImageTimer->isActive()) {
//            _songImageSumPausedTime += _songImageElapsedTimer.elapsed() - _songImageLastPausedTime;
//            _songImageTimer->start(); // 开始旋转
//        }
    }
}

void MusicPlayer::on_playlist_mediaFirstChanged()
{
//    initSongImageTimer();
//    disconnect(_player, &QMediaPlayer::stateChanged, this, &MusicPlayer::on_playlist_mediaFirstChanged);
}

void MusicPlayer::on_playlist_currentIndexFChanged(int currentIndex)
{
    initSongImageTimer();
    QUrl currentUrl = _currentSongs[currentIndex];
    if (SongManager::instance()->exist(currentUrl)){
        updateSongMessage(SongManager::instance()->getSongItem(currentUrl));
        _currentUrl = currentUrl;
        beginPlay(_currentUrl);
    }
    connect(_playlist, &QMediaPlaylist::currentIndexChanged, this, &MusicPlayer::on_playlist_currentIndexChanged);
    disconnect(_playlist, &QMediaPlaylist::currentIndexChanged, this, &MusicPlayer::on_playlist_currentIndexFChanged);
}

void MusicPlayer::on_playlist_currentIndexChanged(int currentIndex)
{
    QUrl currentUrl = _currentSongs[currentIndex];
    if (SongManager::instance()->exist(currentUrl)){
        updateSongMessage(SongManager::instance()->getSongItem(currentUrl));

//        stopPlay(); // 这里不能直接stopPlay,如果是正常切换,会跳过一首歌
        SongManager::instance()->play(_currentUrl, false);
        _songImageTimer->stop(); // 暂停旋转

        _currentUrl = currentUrl;
        beginPlay(_currentUrl);
    }
}

void MusicPlayer::on_playlist_playbackModeChanged(QMediaPlaylist::PlaybackMode mode)
{
    qDebug() << "playbackModeChange to " << mode;
    QString background_image;
    if (mode == QMediaPlaylist::CurrentItemInLoop){
        background_image = "CurrentItemInLoop";
    } else if(mode == QMediaPlaylist::Loop){
        background_image = "Loop";
    } else if(mode == QMediaPlaylist::Random){
        background_image = "Random";
    }
    QString style("QPushButton"
                  "{ background-repeat: no-repeat; background-position: center; border: none; background-color: transparent;"
                    "background-image: url(:/image/ui/btn_" + background_image + "_50.png); }"
                  "QPushButton:hover, QPushButton:pressed "
                  "{ background-image: url(:/image/ui/btn_" + background_image + "_100.png); }");
    ui->pushButton_playbackMode->setStyleSheet(style);
}

void MusicPlayer::on_pushButton_playPause_clicked(bool checked)
{
    if(checked){
        qDebug() << checked << ", play";
        beginPlay(_currentUrl);
    } else {
        qDebug() << checked << ", pause";
        stopPlay();
    }
}

void MusicPlayer::on_pushButton_playNext_clicked()
{
    _playlist->next();
}

void MusicPlayer::on_pushButton_playPrev_clicked()
{
    _playlist->previous();
}



//QMediaPlaylist::CurrentItemOnce  --  不支持
//QMediaPlaylist::CurrentItemInLoop  --  单曲循环
//QMediaPlaylist::Sequential  --  不支持
//QMediaPlaylist::Loop  --  循环
//QMediaPlaylist::Random  --  随机
void MusicPlayer::on_pushButton_playbackMode_clicked()
{
    QMediaPlaylist::PlaybackMode curMode = _playlist->playbackMode();
    if (curMode == QMediaPlaylist::Loop){
        _playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
    } else if (curMode == QMediaPlaylist::CurrentItemInLoop){
        _playlist->setPlaybackMode(QMediaPlaylist::Random);
    } else {
        _playlist->setPlaybackMode(QMediaPlaylist::Loop);
    }
}

void MusicPlayer::on_pushButton_minimize_clicked()
{
    showMinimized();
}


void MusicPlayer::on_pushButton_volume_clicked()
{
    QRect geometry = _volumeTool->geometry();
    QPoint tgt = ui->pushButton_volume->mapToGlobal(QPoint(0, 0));
    geometry.setX(tgt.x() - 10);
    geometry.setY(tgt.y() - geometry.height());
    _volumeTool->setGeometry(geometry);
    _volumeTool->show();
}

bool MusicPlayer::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->pushButton_volume && event->type() == QEvent::Enter) {
        QRect geometry = _volumeTool->geometry();
        QPoint tgt = ui->pushButton_volume->mapToGlobal(QPoint(0, 0));
        geometry.setX(tgt.x() - 20);
        geometry.setY(tgt.y() - geometry.height() + ui->pushButton_volume->height());
        _volumeTool->setGeometry(geometry);
        _volumeTool->show();
        return true;
    }
    if (watched == _volumeTool && event->type() == QEvent::Leave) {
        _volumeTool->hide();
        return true;
    }

    return QWidget::eventFilter(watched, event);
}

void MusicPlayer::on_pushButton_like_clicked()
{
    if(SongManager::instance()->exist(_currentUrl)){
        bool isLike = !SongManager::instance()->getSongItem(_currentUrl).isLike;
        SongManager::instance()->like(_currentUrl, isLike);
        updateLikeButton(isLike);
    } else {
        qDebug() << "当前播放的歌曲不在manager里";
    }
}

void MusicPlayer::on_pushButton_18_clicked()
{
//    _playPage->show();

}
